package com.zhj.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 力扣102 二叉树的层序遍历
 */
public class Test102 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(15);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(7);
        root.right.right = new TreeNode(18);
        List<List<Integer>> res = getRes(root);
        for (List<Integer> re : res) {
            for (Integer i : re) {
                System.out.print(i + "\t");
            }
            System.out.println();
        }
    }

    public static List<List<Integer>> bfs(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> subset = new ArrayList<>();
            while (size > 0) {
                TreeNode cur = queue.poll();
                subset.add(cur.val);
                if (cur.left != null) {
                    queue.add(cur.left);
                }
                if (cur.right != null) {
                    queue.add(cur.right);
                }
                size--;
            }
            result.add(new ArrayList<>(subset));
        }
        return result;
    }

    public static List<List<Integer>> getRes(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        dfs(root, result, 0);
        return result;
    }

    public static void dfs(TreeNode node, List<List<Integer>> result, int level) {
        if (node == null) {
            return;
        }
        if (level > result.size() - 1) {
            result.add(new ArrayList<>());
        }
        result.get(level).add(node.val);
        if (node.left != null) {
            dfs(node.left, result, level+1);
        }
        if (node.right != null) {
            dfs(node.right, result, level+1);
        }
    }
}
